package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.model.Dldysensor;
import com.example.onlinemonitoring.model.Dldyhistory;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.serviceImpl.DldysensorServiceImpl;
import com.example.onlinemonitoring.dao.DldysensorMapper;

import tk.mybatis.mapper.entity.Example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;

import static com.example.onlinemonitoring.Util.CommPortManager.ssList;

import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.net.InetSocketAddress;
import java.net.Socket;
/*这里beanName需要和数据库Appdevice中的simple对应并加上Com,不对应请自行修改
    例:simple:dlhl
    @Service("dlhlCom")
*/
@Service("dldyCom")
@Scope("prototype")
public class DldyCom extends CommPortManager {
        @Autowired
        private DldysensorServiceImpl dldysensorServiceImpl;
        @Autowired
        DldysensorMapper dldymapper;
        int adtype = 0;
        int addrid =0;
        int curraddrindex =0;
        Socket skdl;
         public HashMap<Socket, Integer> skaddr = new HashMap<>();
         //public static Map<AtomicInteger, Socket> ssmap = new HashMap<>();
         public  ArrayList<Integer> skaddrList = new ArrayList<>(); 
        @Override
        public void receiveData(String str) {
            try {
                str = str.toUpperCase();
                setText(str);
                //条件判断自己写
                if ("03".equals(str.substring(2, 4))==false&&str.length()!=48)
                return;

                //地址解析addr
                String addrstr = "";
                if (str.length()==48)
                {
                    addrstr = hexString2String(str);

                }
                
                String ipstr = "";
                skdl=sclsocket;
                InetSocketAddress socketAddress = (InetSocketAddress) skdl.getRemoteSocketAddress();
                String clientIpAddress = socketAddress.getAddress().getHostAddress();
                int clientport = socketAddress.getPort();
                ipstr = clientIpAddress;
                //转地址

                if(addrstr.length()==24)
                {

                    if(addrstr.equals("CLKJ00000000001310421018"))
                    curraddrindex = 18;
                    if(addrstr.equals("CLKJ00000000001310421017"))
                    curraddrindex = 17;
                    if(addrstr.equals("CLKJ00000000001310421016"))
                    curraddrindex = 16;
                    if(addrstr.equals("CLKJ00000000001310421015"))
                    curraddrindex = 15;
                    if(addrstr.equals("CLKJ00000000001310421014"))
                    curraddrindex = 14;
                    if(addrstr.equals("CLKJ00000000001310421013"))
                    curraddrindex = 13;
                    if(addrstr.equals("CLKJ00000000001310421012"))
                    curraddrindex = 12;
                    if(addrstr.equals("CLKJ00000000001310421011"))
                    curraddrindex = 11;
                    if(addrstr.equals("CLKJ00000000001310421010"))
                    curraddrindex = 10;
                    if(addrstr.equals("CLKJ00000000001310421009"))
                    curraddrindex = 9;
                    if(addrstr.equals("CLKJ00000000001310421008"))
                    curraddrindex = 8;
                    if(addrstr.equals("CLKJ00000000001310421007"))
                    curraddrindex = 7;
                    if(addrstr.equals("CLKJ00000000001310421006"))
                    curraddrindex = 6;
                    if(addrstr.equals("CLKJ00000000001310421005"))
                    curraddrindex = 5;
                    if(addrstr.equals("CLKJ00000000001310421004"))
                    curraddrindex = 4;
                    if(addrstr.equals("CLKJ00000000001310421003"))
                    curraddrindex = 3;
                    if(addrstr.equals("CLKJ00000000001310421002"))
                    curraddrindex = 2;
                    if(addrstr.equals("CLKJ00000000001310421001"))
                    curraddrindex = 1;

                    reSend[curraddrindex] = 0;
                    Dldysensor dldysensor = new Dldysensor();
                    //设置设备地址
                    dldysensor.setStationid(ad.getStationid());
                    dldysensor.setDevicegroup(ad.getDevicegroup());
                    dldysensor.setDeviceaddr(curraddrindex);
                    //查询对象
                    Dldysensor record = dldysensorServiceImpl.getModel(dldysensor);
                    if (record == null) {
                        setText("当前数据库无监测点：设备地址" + curraddrindex);
                    }
                    if(curraddrindex==2||curraddrindex==5||curraddrindex==8||curraddrindex==11||curraddrindex==14||curraddrindex==17)
                    adtype=1;
                    else
                    adtype=0;
                    dldysensor.setDeviceid(addrstr);
                    dldysensor.setIpaddr(ipstr);
                    dldysensor.setPort(clientport);
                    dldysensor.setLastalarmlevel(0);
                    dldysensor.setLastalarmmessage("");
                    dldysensor.setLastcommunicationstatus(0);
                    dldysensor.setLastdatatime(new Date());
                    if ( dldysensorServiceImpl.Update(dldysensor, false) == 0) {
                        setText("更新实时数据失败，请检查数据库连接");
                    }
                    return;
                }
                //if(addrid>=skaddrList.size())
                //return;
                //if(!ssList.get(addrid).isClosed())
               // addrindex = skaddrList.get(addrid);
                //reSend[addrindex] = 0;
                //addrindex++;

                Integer startIndex = 12;
                
                // Dldysensor dldysensor = new Dldysensor();
                // //设置设备地址
                // dldysensor.setStationid(ad.getStationid());
                // dldysensor.setDevicegroup(ad.getDevicegroup());
                // dldysensor.setDeviceaddr(addrindex);
                // //查询对象
                // Dldysensor record = dldysensorServiceImpl.getModel(dldysensor);

                Dldysensor dldy = new Dldysensor();
                Example example1 = new Example(Dldysensor.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("stationid", 1);
                //criteria1.andEqualTo("devicegroup", dldy.getDevicegroup());
                //criteria1.andEqualTo("deviceaddr", dldy.getDeviceaddr());
                criteria1.andEqualTo("ipaddr", ipstr);
                criteria1.andEqualTo("port", clientport);
                Dldysensor record = dldymapper.selectOneByExample(example1);
                if (record == null) {
                    setText("当前数据库无监测点：设备地址" + curraddrindex);
                }
                curraddrindex = record.getDeviceaddr();
                reSend[curraddrindex] = 0;
                if(curraddrindex==2||curraddrindex==5||curraddrindex==8||curraddrindex==11||curraddrindex==14||curraddrindex==17)
                adtype=1;
                else
                adtype=0;
                String stlyestr = record.getStyle();
                if(adtype==1)
                {
                    stlyestr="atemper|1|A相表温温度,btemper|1|B相表温温度,ctemper|1|C相表温温度,acurrent|1|A相环流,bcurrent|1|B相环流,ccurrent|1|C相环流,avc|1|A相运行电流,bvc|1|B相运行电流,cvc|1|C相运行电流";
                    dldy.setStyle(stlyestr);
                }
                else
                {
                    stlyestr="atemper|1|A相保护温度,btemper|1|B相保护温度,ctemper|1|C相保护温度,acurrent|1|A相保护运行电流,bcurrent|1|B相保护运行电流,ccurrent|1|C相保护运行电流,avc|1|A相感应电压,bvc|1|B相感应电压,cvc|1|C相感应电压";
                    dldy.setStyle(stlyestr);
                }
                // String atemper = str.substring(22, 22 + 4);
                // String btemper = str.substring(28, 28 + 4);
                // String ctemper = str.substring(34, 34 + 4);
                int atemper = Integer.parseInt(str.substring(42, 42 + 4), 16) ;
                int btemper = Integer.parseInt(str.substring(54, 54 + 4), 16) ;
                int ctemper = Integer.parseInt(str.substring(66, 66 + 4), 16) ;
                float lastacurrnet = Integer.parseInt(str.substring(186, 186 + 4), 16) / 10f;
                float lastbcurrnet = Integer.parseInt(str.substring(198, 198 + 4), 16) / 10f;
                float lastccurrnet = Integer.parseInt(str.substring(210, 210 + 4), 16) / 10f;
                float lastavc = Integer.parseInt(str.substring(234, 234 + 4), 16) / 10f;
                float lastbvc = Integer.parseInt(str.substring(246, 246 + 4), 16) / 10f;
                float lastcvc = Integer.parseInt(str.substring(258, 258 + 4), 16) / 10f;
                float lastatemper = 0;
                float lastbtemper = 0;
                float lastctemper = 0;
                if(atemper>8000){
                    lastatemper = -((atemper^0xFFFF)+1)/10f;}
                else{
                    lastatemper = atemper/10f;}
                if(btemper>8000){
                    lastbtemper = -((btemper^0xFFFF)+1)/10f;}
                else{
                    lastbtemper = btemper/10f;}
                if(ctemper>8000){
                    lastctemper = -((ctemper^0xFFFF)+1)/10f;}
                else{
                    lastctemper = ctemper/10f;}
                setText("电缆接地设备返回数据： 站点号：1 监测点" + curraddrindex);
                if(adtype==1)
                {
                    setText("A相表温温度：" + lastatemper + "A" + " B相表温温度：" + lastbtemper + "A" + " C相表温温度：" + lastctemper+ "A" );
                    setText("A相环流：" + lastacurrnet + "A" + " B相环流：" + lastbcurrnet + "A" + " C相环流：" + lastccurrnet+ "A" );
                    setText("A相运行电流：" + lastavc + "A" + " B相运行电流：" + lastbvc + "A" + " C相运行电流：" + lastcvc+ "A" );
                }
                else
                {
                    setText("A相保护温度：" + lastatemper + "A" + " B相保护温度：" + lastbtemper + "A" + " C相保护温度：" + lastctemper+ "A" );
                    setText("A相保护运行电流：" + lastacurrnet + "A" + " B相保护运行电流：" + lastbcurrnet + "A" + " C相保护运行电流：" + lastccurrnet+ "A" );
                    setText("A相感应电压：" + lastavc + "A" + " B相感应电压：" + lastbvc + "A" + " C相感应电压：" + lastcvc+ "A" );      
                }
                dldy.setDeviceaddr(curraddrindex);
                dldy.setLastadtype(adtype);
                dldy.setLastatemper(lastatemper);
                dldy.setLastbtemper(lastbtemper);
                dldy.setLastctemper(lastctemper);
                dldy.setLastacurrent(lastacurrnet);
                dldy.setLastbcurrent(lastbcurrnet);
                dldy.setLastccurrent(lastccurrnet);
                dldy.setLastavc(lastavc);
                dldy.setLastbvc(lastbvc);
                dldy.setLastcvc(lastcvc);
                AddAndUpdate(record,dldy);

            } catch (Exception ex) {
                ex.printStackTrace();
                setText("从设备返回的数据有误！请检查串口！");
            }
        }

        @Transactional
        private void AddAndUpdate(Dldysensor record,Dldysensor dldysensor) {
            int alarmLevel = 0;// 报警等级
            String alarmMessage = "";// 报警消息
            if (record.getCurrentalarmvlaue() == null ||
                    record.getCurrentalarmrelievevlaue() == null ||
                    record.getCurrentwarnvlaue() == null ||
                    record.getCurrentwarnrelievevlaue() == null ||
                    record.getTemperaturealarmvalue() == null ||
                    record.getTemperaturealarmrelievevalue() == null ||
                    record.getTemperaturewarnvalue() == null ||
                    record.getTemperaturewarnrelievevalue() == null ||
                    record.getVcalarmvlaue() == null ||
                    record.getVcalarmrelievevlaue() == null ||
                    record.getVcwarnrelievevlaue() == null ||
                    record.getVcwarnvlaue() == null
            ) {
                setText("设备地址" + record.getDeviceaddr() + " 未设置报警值！");
                return;
            }
            //报警逻辑
            //这里写报警逻辑
            List<Integer> array = new ArrayList<>();
            if(adtype==1)
            {
                dldysensor.setLastaalarmstatus(
                    GetAlarmStatus(isnull(dldysensor.getLastatemper()), isnull(record.getTemperaturealarmvalue()),
                            isnull(record.getTemperaturealarmrelievevalue()), isnull(record.getTemperaturewarnvalue()),
                            isnull(record.getTemperaturewarnrelievevalue()),
                            isnull(record.getLastaalarmstatus()), true, "A相表温温度", record.getDevicegroup(),
                            record.getDeviceaddr(),
                            record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastaalarmstatus(), "A相表温温度");
                array.add(dldysensor.getLastaalarmstatus());
                dldysensor.setLastbalarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastbtemper()), isnull(record.getTemperaturealarmvalue()),
                                isnull(record.getTemperaturealarmrelievevalue()), isnull(record.getTemperaturewarnvalue()),
                                isnull(record.getTemperaturewarnrelievevalue()),
                                isnull(record.getLastbalarmstatus()), true, "B相表温温度", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastbalarmstatus(), "B相表温温度");
                array.add(dldysensor.getLastbalarmstatus());
                dldysensor.setLastcalarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastctemper()), isnull(record.getTemperaturealarmvalue()),
                                isnull(record.getTemperaturealarmrelievevalue()), isnull(record.getTemperaturewarnvalue()),
                                isnull(record.getTemperaturewarnrelievevalue()),
                                isnull(record.getLastcalarmstatus()), true, "C相表温温度", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastcalarmstatus(), "C相表温温度");
                array.add(dldysensor.getLastcalarmstatus());
                dldysensor.setLasta1alarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastacurrent()), isnull(record.getCurrentalarmvlaue()),
                                isnull(record.getCurrentalarmrelievevlaue()), isnull(record.getCurrentwarnvlaue()),
                                isnull(record.getCurrentwarnrelievevlaue()),
                                isnull(record.getLasta1alarmstatus()), true, "A相环流", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLasta1alarmstatus(), "A相环流");
                array.add(dldysensor.getLasta1alarmstatus());
                dldysensor.setLastb1alarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastbcurrent()), isnull(record.getCurrentalarmvlaue()),
                                isnull(record.getCurrentalarmrelievevlaue()), isnull(record.getCurrentwarnvlaue()),
                                isnull(record.getCurrentwarnrelievevlaue()),
                                isnull(record.getLastb1alarmstatus()), true, "B相环流", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastb1alarmstatus(), "B相环流");
                array.add(dldysensor.getLastb1alarmstatus());
                dldysensor.setLastc1alarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastccurrent()), isnull(record.getCurrentalarmvlaue()),
                                isnull(record.getCurrentalarmrelievevlaue()), isnull(record.getCurrentwarnvlaue()),
                                isnull(record.getCurrentwarnrelievevlaue()),
                                isnull(record.getLastc1alarmstatus()), true, "C相环流", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastc1alarmstatus(), "C相环流");
                array.add(dldysensor.getLastc1alarmstatus());
                dldysensor.setLastavcalarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastavc()), isnull(record.getVcalarmvlaue()),
                                isnull(record.getVcalarmrelievevlaue()), isnull(record.getVcwarnvlaue()),
                                isnull(record.getVcwarnrelievevlaue()),
                                isnull(record.getLastavcalarmstatus()), true, "A相运行电流", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastavcalarmstatus(), "A相运行电流");
                array.add(dldysensor.getLastavcalarmstatus());
                dldysensor.setLastbvcalarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastbvc()), isnull(record.getVcalarmvlaue()),
                                isnull(record.getVcalarmrelievevlaue()), isnull(record.getVcwarnvlaue()),
                                isnull(record.getVcwarnrelievevlaue()),
                                isnull(record.getLastbvcalarmstatus()), true, "B相运行电流", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastbvcalarmstatus(), "B相运行电流");
                array.add(dldysensor.getLastbvcalarmstatus());
                dldysensor.setLastcvcalarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastcvc()), isnull(record.getVcalarmvlaue()),
                                isnull(record.getVcalarmrelievevlaue()), isnull(record.getVcwarnvlaue()),
                                isnull(record.getVcwarnrelievevlaue()),
                                isnull(record.getLastcvcalarmstatus()), true, "C相运行电流", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastcvcalarmstatus(), "C相运行电流");
                array.add(dldysensor.getLastcvcalarmstatus());
            }
            else
            {
                dldysensor.setLastaalarmstatus(
                    GetAlarmStatus(isnull(dldysensor.getLastatemper()), isnull(record.getTemperaturealarmvalue()),
                            isnull(record.getTemperaturealarmrelievevalue()), isnull(record.getTemperaturewarnvalue()),
                            isnull(record.getTemperaturewarnrelievevalue()),
                            isnull(record.getLastaalarmstatus()), true, "A相保护温度", record.getDevicegroup(),
                            record.getDeviceaddr(),
                            record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastaalarmstatus(), "A相保护温度");
                array.add(dldysensor.getLastaalarmstatus());
                dldysensor.setLastbalarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastbtemper()), isnull(record.getTemperaturealarmvalue()),
                                isnull(record.getTemperaturealarmrelievevalue()), isnull(record.getTemperaturewarnvalue()),
                                isnull(record.getTemperaturewarnrelievevalue()),
                                isnull(record.getLastbalarmstatus()), true, "B相保护温度", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastbalarmstatus(), "B相保护温度");
                array.add(dldysensor.getLastbalarmstatus());
                dldysensor.setLastcalarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastctemper()), isnull(record.getTemperaturealarmvalue()),
                                isnull(record.getTemperaturealarmrelievevalue()), isnull(record.getTemperaturewarnvalue()),
                                isnull(record.getTemperaturewarnrelievevalue()),
                                isnull(record.getLastcalarmstatus()), true, "C相保护温度", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastcalarmstatus(), "C相保护温度");
                array.add(dldysensor.getLastcalarmstatus());
                dldysensor.setLasta1alarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastacurrent()), isnull(record.getCurrentalarmvlaue()),
                                isnull(record.getCurrentalarmrelievevlaue()), isnull(record.getCurrentwarnvlaue()),
                                isnull(record.getCurrentwarnrelievevlaue()),
                                isnull(record.getLasta1alarmstatus()), true, "A相保护运行电流", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLasta1alarmstatus(), "A相保护运行电流");
                array.add(dldysensor.getLasta1alarmstatus());
                dldysensor.setLastb1alarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastbcurrent()), isnull(record.getCurrentalarmvlaue()),
                                isnull(record.getCurrentalarmrelievevlaue()), isnull(record.getCurrentwarnvlaue()),
                                isnull(record.getCurrentwarnrelievevlaue()),
                                isnull(record.getLastb1alarmstatus()), true, "B相保护运行电流", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastb1alarmstatus(), "B相保护运行电流");
                array.add(dldysensor.getLastb1alarmstatus());
                dldysensor.setLastc1alarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastccurrent()), isnull(record.getCurrentalarmvlaue()),
                                isnull(record.getCurrentalarmrelievevlaue()), isnull(record.getCurrentwarnvlaue()),
                                isnull(record.getCurrentwarnrelievevlaue()),
                                isnull(record.getLastc1alarmstatus()), true, "C相保护运行电流", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastc1alarmstatus(), "C相保护运行电流");
                array.add(dldysensor.getLastc1alarmstatus());
                dldysensor.setLastavcalarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastavc()), isnull(record.getVcalarmvlaue()),
                                isnull(record.getVcalarmrelievevlaue()), isnull(record.getVcwarnvlaue()),
                                isnull(record.getVcwarnrelievevlaue()),
                                isnull(record.getLastavcalarmstatus()), true, "A相感应电压", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastavcalarmstatus(), "A相感应电压");
                array.add(dldysensor.getLastavcalarmstatus());
                dldysensor.setLastbvcalarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastbvc()), isnull(record.getVcalarmvlaue()),
                                isnull(record.getVcalarmrelievevlaue()), isnull(record.getVcwarnvlaue()),
                                isnull(record.getVcwarnrelievevlaue()),
                                isnull(record.getLastbvcalarmstatus()), true, "B相感应电压", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastbvcalarmstatus(), "B相感应电压");
                array.add(dldysensor.getLastbvcalarmstatus());
                dldysensor.setLastcvcalarmstatus(
                        GetAlarmStatus(isnull(dldysensor.getLastcvc()), isnull(record.getVcalarmvlaue()),
                                isnull(record.getVcalarmrelievevlaue()), isnull(record.getVcwarnvlaue()),
                                isnull(record.getVcwarnrelievevlaue()),
                                isnull(record.getLastcvcalarmstatus()), true, "C相感应电压", record.getDevicegroup(),
                                record.getDeviceaddr(),
                                record.getPointname()));
                alarmMessage += GetAlarmMessage(dldysensor.getLastcvcalarmstatus(), "C相感应电压");
                array.add(dldysensor.getLastcvcalarmstatus());
            }
           

            alarmLevel = HexUtil.MAX(array);
            dldysensor.setLastalarmlevel(alarmLevel);
            dldysensor.setLastalarmmessage(alarmMessage);
            dldysensor.setLastcommunicationstatus(0);
            dldysensor.setLastdatatime(new Date());
            dldysensor.setLasthisdatatime(addHistory(record));
            if ( dldysensorServiceImpl.Update(dldysensor, false) == 0) {
                setText("更新实时数据失败，请检查数据库连接");
            }
        }
        private Date addHistory(Dldysensor sensor) {
            if (sensor != null) {
                if (sensor.getLasthisdatatime() == null) {
                    add(sensor);
                    return new Date();
                } else {
                    long lasttime = 0;
                    long nowtime = 0;
                    try {
                        lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                        nowtime = HexUtil.todate(new Date()).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    int timersp = 60000;
                    if (sensor.getLastalarmlevel() != 0) {
                        timersp = ad.getHisalarmtimersp()*1000;
                    } else {
                        timersp = ad.getHistimersp()*1000;
                    }
                    if (lasttime + timersp < nowtime) {
                        add(sensor);
                        return new Date();
                    }
                }
            }
            return null;
        }

        private void add(Dldysensor sensor) {
            Dldyhistory his = new Dldyhistory();
            his.setDeviceaddr(sensor.getDeviceaddr());
            his.setDevicegroup(sensor.getDevicegroup());
            his.setAlarmlevel(sensor.getLastalarmlevel());
            his.setAlarmmessage(sensor.getLastalarmmessage());
            his.setDatatime(sensor.getLastdatatime());
            his.setPointname(sensor.getPointname());
            his.setStationid(sensor.getStationid());
            //需要添加自己定义的属性
            his.setAtemper(sensor.getLastatemper());
            his.setAalarmstatus(sensor.getLastaalarmstatus());
            his.setBtemper(sensor.getLastatemper());
            his.setBalarmstatus(sensor.getLastaalarmstatus());
            his.setCtemper(sensor.getLastatemper());
            his.setCalarmstatus(sensor.getLastaalarmstatus());
            his.setAcurrent(sensor.getLastacurrent());
            his.setA1alarmstatus(sensor.getLasta1alarmstatus());
            his.setBcurrent(sensor.getLastbcurrent());
            his.setB1alarmstatus(sensor.getLastb1alarmstatus());
            his.setCcurrent(sensor.getLastccurrent());
            his.setC1alarmstatus(sensor.getLastc1alarmstatus());
            his.setAvc(sensor.getLastavc());
            his.setAvcalarmstatus(sensor.getLastavcalarmstatus());
            his.setBvc(sensor.getLastbvc());
            his.setBvcalarmstatus(sensor.getLastbvcalarmstatus());
            his.setCvc(sensor.getLastcvc());
            his.setCvcalarmstatus(sensor.getLastcvcalarmstatus());
            his.setAdtype(sensor.getLastadtype());
            his.setDatatime(sensor.getLastdatatime());
            his.setMemo(sensor.getMemo());
            his.setPointname(sensor.getPointname());
            his.setStationid(sensor.getStationid());
            his.setStyle(sensor.getStyle());
            dldysensorServiceImpl.Add(his);
        }


        @Async("threadPool")
        public void startSendThread(Appdevice Appdevice) throws Exception {

            checkType = "crc16";
            issend.put(Thread.currentThread().getId(), true);
            String cstr = "";
            String cmdtype = "";
            String nametype = "";

            int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
            while (issend.get(Thread.currentThread().getId()) != null) {
                if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                    addrindex = Appdevice.getAddrmin();
                    if(addrid>=ssList.size())
                    addrid=0;
                //cstr = String.format(Appdevice.getCmd(), String.format("%02X", addrindex));
                cstr ="01030001004F";
                cstr = cstr + CRC16.calcCrc16(cstr);
                try {
                    if(ssList.size()>0)
                    {
                        //InputStream is = ssList.get(addrint).getInputStream();
                        if(!ssList.get(addrid).isClosed())
                        Sendtcp(cstr,ssList.get(addrid));
                        else
                        {
                         ssList.remove(addrid);   
                         //skaddrList.remove(addrid);                          
                        }
                      
                    }

                } catch (Exception EX) {
                     setText(EX.toString());
                     ssList.remove(addrid);     
                }
                setText("向" +(addrid+1)+ Appdevice.getName() + "设备发送指令" + cstr);
                reSend[addrindex]++;
                if (reSend[addrindex] > 3) {
                dldysensorServiceImpl.UpdateStatus(ad, addrindex,1);
                reSend[addrindex] = 0;
               // addrid++;
                }
                Thread.sleep(timersp);

                addrid ++;
                addrindex++;
            }
        }

        // @Async("threadPool")
        // public void startReceiveThread(){
        //     isrecv.put(Thread.currentThread().getId(), true);
        //     while (isrecv.get(Thread.currentThread().getId()) != null) {
        //         //这里根据实际协议替换,解析方法recvCrc16;recvSum();
        //         recv();
        //         try {
        //             Thread.sleep(interval);
        //         } catch (InterruptedException e) {
        //             e.printStackTrace();
        //         }
        //     }
        // }
}
